import { defineComponent, PropType, ref, VNode, watch } from 'vue';
import { useNamespace } from '@ibiz-template/vue3-util';
import './crm-page.scss';
import { IDEForm } from '@ibiz/model-core';
import { FormPageController } from '@ibiz-template/runtime';

export const CrmPage = defineComponent({
  name: 'IBizCrmPage',
  props: {
    modelData: {
      type: Object as PropType<IDEForm>,
      required: true,
    },
  },
  setup(_props, { slots, emit }) {
    const ns = useNamespace('crm-page');

    const defaultSlots: VNode[] =
      (slots.default?.()[0]?.children as VNode[]) || [];
    const defaultValue = defaultSlots[0]?.key;
    const tabValue = ref(defaultValue);

    watch(tabValue, () => {
      const index = defaultSlots.findIndex(item => item.key === tabValue.value);
      emit('tab-change', tabValue.value, index !== -1 ? index : 0);
    });

    const handleClick = (id: string): void => {
      tabValue.value = id;
    };

    return { ns, tabValue, handleClick };
  },
  render() {
    const { noTabHeader } = this.modelData;
    const defaultSlots: VNode[] =
      (this.$slots.default?.()[0]?.children as VNode[]) || [];
    if (defaultSlots.length === 1 || noTabHeader) {
      return (
        <div class={[this.ns.b(), this.ns.m('no-tab-header')]}>
          {defaultSlots}
        </div>
      );
    }
    return (
      <div class={this.ns.b()}>
        <el-tabs class={this.ns.b('content')} v-model={this.tabValue}>
          {defaultSlots.map(slot => {
            const { props } = slot;
            if (!props || !props.controller) {
              return slot;
            }
            const c = props.controller as FormPageController;
            // 不显示且不用保活时直接不绘制
            if (!c.state.visible && !c.state.keepAlive) {
              return null;
            }
            return (
              <el-tab-pane class={this.ns.b('tab-item')} name={c.model.id} lazy>
                {{
                  default: (): VNode => slot,
                  label: (): JSX.Element => {
                    return (
                      <span class={c.labelClass}>
                        {c.model.sysImage ? (
                          <iBizIcon icon={c.model.sysImage} />
                        ) : null}
                        {c.model.caption}
                      </span>
                    );
                  },
                }}
              </el-tab-pane>
            );
          })}
        </el-tabs>
      </div>
    );
  },
});
